<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2017/5/11
 * Time: 9:20
 */

namespace SDXApi\Service;


use SDXApi\Model\CommunityAuthorModel;
use SDXApi\Model\CommunityCatModel;
use SDXApi\Model\CommunityCommentGoodsModel;
use SDXApi\Model\CommunityLikeModel;
use SDXApi\Model\CommunityModel;
use SDXApi\Model\CommunityTemplateContentModel;
use SDXApi\Model\CommunityTemplateGoodsModel;
use SDXApi\Model\CommunityTemplateModel;
use SDXApi\Model\GoodsModel;
use SDXApi\Model\SeminarModel;
use SDXApi\Repositories\GoodsRepository;

/**
 * Class CommunityService
 * @package SDXApi\Service
 */
class CommunityNewService
{
    /**
     * @var CommunityModel
     */
    protected $communityModel;

    /**
     * @var CommunityLikeModel
     */
    protected $communityLikeModel;

    /**
     * @var CommunityAuthorModel
     */
    protected $communityAuthorModel;

    /**
     * @var GoodsModel
     */
    protected $goodsModel;

    /**
     * @var GoodsRepository
     */
    protected $goodsRepository;

    /**
     * @var CommunityTemplateModel
     */
    protected $templateModel;

    /**
     * @var CommunityTemplateContentModel
     */
    protected $templateContent;

    /**
     * @var CommunityTemplateGoodsModel
     */
    protected $templateGoods;

    /**
     * @var CommunityCatModel
     */
    protected $communityCatModel;

    /**
     * @var SeminarModel
     */
    protected $seminarModel;

    /**
     * @var AlbumService
     */
    protected $albumService;

    /**
     * @var RecommendService
     */
    protected $recommendService;

    /**
     * @var
     */
    protected $commentGoodsModel;

    /**
     * CommunityService constructor.
     */
    public function __construct()
    {
        $this->communityModel = new CommunityModel();
        $this->communityLikeModel = new CommunityLikeModel();
        $this->communityAuthorModel = new CommunityAuthorModel();
        $this->goodsModel = new GoodsModel();
        $this->goodsRepository = new GoodsRepository();
        $this->templateModel = new CommunityTemplateModel();
        $this->templateContent = new CommunityTemplateContentModel();
        $this->templateGoods = new CommunityTemplateGoodsModel();
        $this->communityCatModel = new CommunityCatModel();
        $this->seminarModel = new SeminarModel();
        $this->recommendService = new RecommendService();
        $this->albumService = new AlbumService();
        $this->commentGoodsModel = new CommunityCommentGoodsModel();
    }

    /**
     * Created by Jerry
     * @param int $id
     * @param int $uid
     * @param int $wid
     * @return mixed
     */
    public function getArticleDetail($id = 0, $uid = 0, $wid = 8)
    {
        $data = $this->getArticleData($id, $uid, $wid);

        return $data;
    }

    /**
     * @author Jerry
     * @param int $id
     * @param int $uid
     * @param int $wid
     * @return array|bool|mixed
     */
    protected function getArticleData($id = 0, $uid = 0, $wid = 8)
    {
        $article =  $this->communityModel->findCommunityInfo($id);

        $this->goodsRepository->userId = $uid;
        $this->goodsRepository->wid = $wid;
        $templates = $this->templateModel->findTemplatesByCommunityId($article['community_id']);

        if (! empty($templates)) {
            foreach ($templates as $key => $value) {
                $result = $this->getTemplateInfoData($value, $uid, $wid);
                if (empty($result)) {
                    continue;
                }

                if ($value['template_type'] == 1) {
                    $result['content'] = $this->setContentImageHost($result['content']);
                    $result['content'] = $this->setContentImageHttps($result['content']);
                    $result['content'] = $this->setContentWImageHttps($result['content']);
                    $result['content'] = $this->getContentGoodsId($result['content'], $wid);
                    $result['content'] = $this->setContentStyle($result['content']);
                    $templates[$key]['content'] = $result['content'];
                }

                if ($value['template_type'] == 2) {
                    $templates[$key]['goods_list'] = $result;
                }
            }

            $article['article_data'] = $templates;
        }



        $article['content'] = $this->setContentImageHost($article['content']);
        $article['content'] = $this->setContentImageHttps($article['content']);
        $article['content'] = $this->setContentWImageHttps($article['content']);
        $article['content'] = $this->getContentGoodsId($article['content'], $wid);
        $article['content'] = $this->setContentStyle($article['content']);

        $count = $this->communityLikeModel->getCount($id, $uid);
        if ($count > 0) {
            $article['like'] = '1';
        } else {
            $article['like'] = '0';
        }

        $article['author_'] = '0';

        $this->communityModel->setCommunityInc('reading_times', $id);

        $this->communityAuthorModel->setCommunityAuthorInc('reading_times', $article['author_id']);
        return $article;
    }

    /**
     * @author Jerry
     * @param array $data
     * @param int $uid
     * @param int $wid
     * @return array|bool|mixed
     */
    protected function getTemplateInfoData($data = array(), $uid = 0, $wid = 8)
    {
        if ($data['template_type'] == 1) {
            return $this->getTemplateContent($data['id']);
        }

        if ($data['template_type'] == 2) {
            return $this->getTemplateGoods($data['id'], $uid, $wid);
        }

        return false;
    }

    /**
     * @author Jerry
     * @param int $template_id
     * @return bool|mixed
     */
    protected function getTemplateContent($template_id = 0)
    {
        $content = $this->templateContent->findContentByTemplateId($template_id);

        if (empty($content)) {
            return false;
        }

        $content['content'] = $this->setContentImageHost($content['content']);
        $content['content'] = $this->setContentImageHttps($content['content']);
        $content['content'] = $this->setContentWImageHttps($content['content']);
        $content['content'] = $this->setContentStyle($content['content']);

        return $content;
    }

    /**
     * @author Jerry
     * @param int $template_id
     * @param int $uid
     * @param int $wid
     * @return array|bool
     */
    protected function getTemplateGoods($template_id = 0, $uid = 0, $wid = 8)
    {
        $goods = $this->templateGoods->findGoodsListByTemplateId($template_id, $wid);
        if (empty($goods)) {
            return false;
        }

        $goodsFormatData = $this->goodsRepository->formatGoodsTransform($goods);

        if (empty($goodsFormatData)) {
            return false;
        }

        return $goodsFormatData;
    }

    /**
     * Created by Jerry
     * @param null $content
     * @param int $wid
     * @return bool|mixed|null
     */
    protected function getContentGoodsId($content = null, $wid = 8)
    {
        $replace = '/{{ goods_id=([0-9]+) }}/';
        preg_match_all($replace, $content, $goods);

        if (empty($goods)) {
            return false;
        }

        $goods_ids = $goods[1];

        foreach ($goods_ids as $key => $value) {
            $result = $this->getGoodsInfo($value, $wid);

            $str = "{{ goods_id={$value} }}";

            if (empty($result)) {
                $content = str_replace($str, '', $content);
            }


            $content = str_replace($str, $result, $content);
        }

        return $content;
    }

    /**
     * Created by Jerry
     * @param $id
     * @param $wid
     * @return bool|string
     */
    protected function getGoodsInfo($id, $wid)
    {
        $goods = $this->goodsModel->getArticleGoods($id, $wid);
        $goodsInfo = $this->goodsRepository->formatGoodsArticleTransform($goods);

        if (empty($goodsInfo)) {
            return false;
        }

        return $this->goodsTemplate($goodsInfo);
    }

    /**
     * Created by Jerry
     * @param array $goods
     * @return string
     */
    protected function goodsTemplate($goods = array())
    {
        $html = <<<FOO
        <a href="https://#!/info?id={$goods['goods_id']}">
        <div style="height: 3.3rem;border-bottom: .5px solid #dedede;background: #fff;position: relative;border-top: 1px solid #fff;margin-bottom:0;overflow:hidden;">
		<div style="float:left;width: 3.3rem;height: 3.3rem;position: relative;top: 0;left: 0;">
			<img src="https://image.shidexian.com/{$goods['original_img']}" style="width:3.3rem;height:3.3rem;">
		</div>
		<div style="margin-left: 3.6rem;height: 100%;position: relative;margin-right: 14px;">
			<p style="margin: .1rem 0;white-space:nowrap;overflow: hidden;text-overflow: ellipsis;line-height: .44rem;margin-top: 0;top: .35rem;font-size: .4rem;color: #393939;position: absolute;left: 0;width: 100%;">{$goods['goods_name']}</p>
			<p style="white-space:nowrap;overflow: hidden;text-overflow: ellipsis;margin-bottom: .03rem;position: absolute;left: 0;width: 100%;font-size: .32rem;color: #777;line-height: .48rem;top: .826rem;">{$goods['goods_brief']}</p>
			<p style="font-size:.266rem;bottom: 1rem;line-height:.4rem;margin-top: 0;top: 1.3rem;color: #ff4463;position: absolute;left: 0;">
				<span style="display:inline-block;background:#fff;margin-right: 3px;border: .5px solid #75a342;border-radius: .43rem;color: #75a342;height: .42rem;line-height: .42rem;padding: 0 4px;font-size: .26rem;">1个</span>
				<span style="display:inline-block;background:#fff;margin-right: 3px;border: .5px solid #75a342;border-radius: .43rem;color: #75a342;height: .42rem;line-height: .42rem;padding: 0 4px;font-size: .26rem;">起够数量2份</span>
			</p>
		</div>
		<div style="position: absolute;left: 0;display: block;width: 100%;padding-left: 3.6rem;    bottom: 0;border-bottom: 0;background: none;height: .92rem;top: 2.3rem;">
			<div style="border-top:0;">
				<div style="left: 3.6rem;color: #ff5870;vertical-align: baseline;z-index:1;bottom: 0;top: auto;padding-top: 0;position: static;">
					<div style="display:inline-block;font-size:.37rem;color: #ff4562;">￥</div>
					<div style="position: relative;top: 1px;display: inline-block;margin-left:-4px;font-size: .4rem;line-height: .53rem;color: #ff4562;">{$goods['market_price']}</div>
					<div style="margin-left: 1px;text-decoration: none;display: none;font-size: .29rem;line-height: .346rem;position: static;margin-top: 0;">￥{$goods['vip_price']}</div>
					<div style="margin-left:1px;color:#393939;text-decoration: none;display:block;font-size: .29rem;line-height: .346rem;position: static;margin-top: 0;">VIP会员价￥{$goods['true_vip_price']}</div>
				</div>
			</div>
		</div>
	</div>
    </a>
FOO;

        return $html;

    }

    /**
     * Created by Jerry
     * @param null $content
     * @return bool|mixed
     */
    protected function setContentImageHost($content = null)
    {
        if (empty($content)) {
            return false;
        }

        $thisUrl = '';
        switch ($_SERVER['SERVER_NAME']) {
            case 'api.xian3.com':
                $thisUrl = 'image.xian3.com';
                break;
            case 'api.shidexian.dev':
                $thisUrl = 'image.shidexian.dev';
                break;
            case 'api.test.shidexian.com':
                $thisUrl = 'image.shidexian.com';
                break;
            case 'api.shidexian.com':
                $thisUrl = 'image.shidexian.com';
                break;
            default:
                $thisUrl = 'image.shidexian.com';
                break;
        }

        return preg_replace('/(<img.+?src=")(\/.*?)/', '$1https://' . $thisUrl . '$2', $content);
    }

    /**
     * Created by Jerry
     * @param null $content
     * @return mixed
     */
    protected function setContentImageHttps($content = null)
    {
        $data = str_replace('http:', 'https:', $content);
        return $data;
    }

    /**
     * Created by Jerry
     * @param null $content
     * @return mixed
     */
    protected function setContentWImageHttps($content = null)
    {
        $data = str_replace('w.shidexian', 'image.shidexian', $content);
        return $data;
    }

    /**
     * @author Jerry
     * @param null $content
     * @return mixed|null
     */
    protected function setContentStyle($content = null)
    {
        $content = preg_replace('/(<img.+)(!important+)/', '$1', $content);
        $content = preg_replace('/(<section .+)(padding-right:2px;+)/', '$1', $content);
        $content = preg_replace('/(<section .+)(display:inline-block;+)/', '$1', $content);
        $content = preg_replace('/(<section .+)(width:50%;+)/', '$1', $content);
        return $content;
    }

    /**
     * @author Jerry
     * @param int $userId
     * @return mixed
     */
    public function getCollectArticle($userId = 0)
    {
        if (empty($userId)) {
            return false;
        }

        $list = $this->findCollectArticle($userId);
        return $list;
    }

    /**
     * @author Jerry
     * @param int $userId
     * @return mixed
     */
    protected function findCollectArticle($userId = 0)
    {
        return $this->communityLikeModel->findCollectByUserId($userId);
    }

    /**
     * @author Jerry
     * @param int $author_id
     * @param int $uid
     * @param int $current_page
     * @param int $start
     * @param int $page_current
     * @return mixed
     */
    public function getCommunityList($author_id = 0, $uid = 0, $current_page = 1, $start = 0, $page_current = 1)
    {
        $list = $this->communityModel->findCommunityByAuthorId($author_id, $start);

        $author = $this->communityAuthorModel->findCommunityAuthorByAuthorId($author_id);

        $listarr = array();
        $listitem = array();

        foreach ($list as $key => $val) {

            $list[$key]['time'] = $this->time_tran($val['add_time']);
            $count = $this->communityLikeModel->getCount($val['community_id'], $uid);

            if ($count > 0) {
                $list[$key]['like'] = '1';
            } else {
                $list[$key]['like'] = '0';
            }

        }

        foreach ($list as $key => $val) {

            if (in_array(local_date("Y-m-d", $val['add_time']), $listitem)) {
                foreach ($listarr as $ikey => $ival) {
                    if ($ival['date'] == local_date("Y-m-d", $val['add_time'])) {
                        $listarr[$ikey]['article'][] = $val;
                    }
                }
            } else {
                $listarrtemp = array();
                $listarrtemp['date'] = local_date("Y-m-d", $val['add_time']);
                $listarrtemp['article'][] = $val;
                $listarr[] = $listarrtemp;
                $listitem[] = local_date("Y-m-d", $val['add_time']);
            }

        }

        $community_count = $this->communityModel->getAuthorCount($author_id);
        $community_list['author'] = $author;
        $community_list['list'] = $listarr;
        $community_list['page_count'] = ceil($community_count / 20);
        $community_list['count'] = $community_count;
        $community_list['page_current'] = $page_current;
        $community_list['is_bottom'] = 0;
        if ($page_current == $community_list['page_count'] || $community_list['page_count'] == 0) {
            $community_list['is_bottom'] = 1;
        }

        //添加行为
        $user_behavior = new UserBehavior();
        if ($current_page == 1) {
            $user_behavior->add_community_browse($uid, 5, $author_id, $author['author']);
        }
        $user_behavior->add_community_exposure($uid, 2, $list);

        return $community_list;
    }

    /**
     * @author Jerry
     * @param $show_time
     * @return string
     */
    protected function time_tran($show_time)
    {
        $the_time = '';

        $now_time = strtotime("now");
        $dur = $now_time - $show_time;
        if ($dur < 0) {
            return $the_time;
        } else {
            if ($dur < 60) {
                return $dur . '秒前';
            } else {
                if ($dur < 3600) {
                    return floor($dur / 60) . '分钟前';
                } else {
                    if ($dur < 86400) {
                        return floor($dur / 3600) . '小时前';
                    } else {
                        if ($dur < 259200) {//3天内
                            return floor($dur / 86400) . '天前';
                        } else {
                            return local_date("m-d", $show_time);
                        }
                    }
                }
            }
        }
    }

    /**
     * 获取文章列表
     * @author Jerry
     * @param int $cat_id
     * @param int $uid
     * @param int $current_page
     * @param int $start
     * @param int $page_current
     * @return mixed
     */
    public function getArticleList($cat_id = 0, $uid = 0, $current_page = 0, $start = 0, $page_current = 1)
    {
        $wid = I('post.wid', 8, 'int');
        $cat_id_arr = $this->getCategoryData($cat_id);

        $list = $this->communityModel->findCommunityInCatId($cat_id_arr, $start);
        $comment = $this->commentGoodsModel->findCommentGoods($start, $wid);

        $goodsRepository = new GoodsRepository($uid, $wid);
        $comment = $goodsRepository->formatGoodsTransform($comment);

        $data = $this->getCommunityArticleListData($uid, $comment, $cat_id_arr);

        $pagination = $this->getCommunityCommentPagination($page_current);

        $result = array();
        $result['data'] = $data;
        $result['page'] = $pagination;

        $result['is_bottom'] = 0;
        if ($page_current == $pagination['page_count'] || $pagination['page_count'] == 0) {
            $result['is_bottom'] = 1;
        }

        $this->addUserBehavior($uid, $cat_id, $list, $current_page);

        return $result;
    }

    /**
     * 获取分类数据
     * @author Jerry
     * @param int $cat_id
     * @return array
     */
    protected function getCategoryData($cat_id = 0)
    {
        $cat_id_arr = array($cat_id);
        $community_count = $this->communityCatModel->getCommunityCatCountByCatId($cat_id);

        if ($community_count > 0) {
            $c_cat = $this->communityCatModel->findCommunityListCatByCatId($cat_id);

            foreach ($c_cat as $item) {
                $cat_id_arr[] = $item['cat_id'];
            }
        }

        return $cat_id_arr;
    }

    /**
     * @author Jerry
     * @param int $uid
     * @param array $list
     * @param array $category_id
     * @param int $start
     * @return array
     */
    protected function getCommunityArticleListData($uid = 0, $list = array(), $category_id = array(), $start = 0)
    {
        if (empty($uid) || empty($list)) {
            return array();
        }

//        $seminars = $this->getSeminars();
        $albums = $this->albumService->getArticleAlbums();
//        $comment = $this->commentGoodsModel->findCommentGoods();

        foreach ($list as $key => $value) {
            $comment_image = $this->commentGoodsModel->findCommentImageByCommentId($value['comment_id']);

            if (empty($comment_image)) {
                unset($list[$key]);
                continue;
            }
            unset($list[$key]['goods_desc']);
            $list[$key]['add_time'] = gmtime($value['add_time']);
//            dd($this->unicode2utf8($value['content']));
            $list[$key]['content'] = $this->unicode2utf8($value['content']);
            $list[$key]['comment_images'] = $comment_image;
            $list[$key]['comment_image_count'] = count($comment_image);
        }
//        dd($list);
        $list = array_merge($list);

        $forNumber = count($list);

        $data = array();

        $goods = $this->recommendService->get_goods_by_discover($uid, $forNumber, 5);

        $community = $this->communityModel->findCommunityInCatId($category_id, $start);
        foreach ($community as $key => $val) {
            $community[$key]['add_time'] = $this->time_tran($val['add_time']);
            $community[$key]['like'] = $this->communityLikeModel->findCommunityLikeByIdAndUserId($val['community_id'], $uid);
        }


//        $twoGoods = $this->recommendService->get_goods_by_discover($uid, $forNumber, 2);

        for ($i = 0; $i < $forNumber; $i++) {

            $data[] = array(
                'data'  =>  $community[$i],
                'type'  =>  1,
            );

            if (! empty($goods)) {
                $data[] = array(
                    'data'  =>  array_slice($goods[$i], 0, 3),
                    'type'  =>  2,
                );
            }

            $data[] = array(
                'data'  =>  $list[$i],
                'type'  =>  4,
            );

            if (! empty($albums)) {
                $seminarKey = array_rand($albums, 1);
                $data[] = array(
                    'data'  =>  $albums[$seminarKey],
                    'type'  =>  3,
                );
            }

            if (! empty($goods)) {
                $data[] = array(
                    'data'  =>  array_slice($goods[$i], -2),
                    'type'  =>  2,
                );
            }
        }

        return $data;
    }

    protected function unicode2utf8($name = '')
    {
        //转换编码，将Unicode编码转换成可以浏览的utf-8编码
        $pattern = '/([\w]+)|(\\\u([\w]{4}))/i';
        preg_match_all($pattern, $name, $matches);

        if (!empty($matches))
        {

            foreach ($matches as $key => $value) {
                if (empty($value)) {
                    return $name;
                }
            }

            $name = '';
            for ($j = 0; $j < count($matches[0]); $j++)
            {
                $str = $matches[0][$j];
                if (strpos($str, '\\u') === 0)
                {
                    $code = base_convert(substr($str, 2, 2), 16, 10);
                    $code2 = base_convert(substr($str, 4), 16, 10);
                    $c = chr($code).chr($code2);
                    $c = iconv('UCS-2', 'UTF-8', $c);
                    $name .= $c;
                }
                else
                {
                    $name .= $str;
                }
            }
        }

        return $name;
    }

    /**
     * 获取有效的专题数据
     * @author Jerry
     * @return array|mixed
     */
    protected function getSeminars()
    {
        $seminars = $this->seminarModel->findSeminarListByStatus();

        if (empty($seminars)) {
            return array();
        }

        foreach ($seminars as $key => $value) {
            if (! empty($value['image'])) {
                $seminars[$key]['image'] = self::checkImageUrlReplace($value['image']);
            }
        }

        return $seminars;
    }

    /**
     * 获取文章列表分页数据
     * @author Jerry
     * @param int $cat_id
     * @param int $page_current
     * @return array
     */
    protected function getCommunityArticleListPagination($cat_id = 0, $page_current = 0)
    {
        $community_count = $this->communityModel->getCommunityCountByCatId($cat_id);
        $pagination = array(
            'count' =>  $community_count,
            'page_count'    =>  ceil($community_count / 20),
            'page_current'  =>  $page_current,
        );

        return $pagination;
    }

    /**
     * @author Jerry
     * @param int $page_current
     * @return array
     */
    protected function getCommunityCommentPagination($page_current = 0)
    {
        $community_count = $this->commentGoodsModel->findCommentGoodsCount();
        $pagination = array(
            'count' =>  $community_count,
            'page_count'    =>  ceil($community_count / 20),
            'page_current'  =>  $page_current,
        );

        return $pagination;
    }

    /**
     * 添加用户行为
     * @author Jerry
     * @param int $uid
     * @param int $cat_id
     * @param array $list
     * @param int $current_page
     */
    protected function addUserBehavior($uid = 0, $cat_id = 0, $list = array(), $current_page = 0)
    {
        //添加行为
        $user_behavior = new UserBehavior();
        $cat_name = $this->communityCatModel->where(array('cat_id' => $cat_id))->getField('cat_name');
        if ($current_page == 1) {
            $user_behavior->add_community_browse($uid, 1, $cat_id, $cat_name);
        }
        $user_behavior->add_community_exposure($uid, 1, $list);
    }

    /**
     * url地址替换
     * @author Jerry
     * @param $url
     * @return mixed
     */
    static protected function checkImageUrlReplace($url)
    {

        $urlPos = strpos($url, '//oss.shidexian.com');
        if ($urlPos !== false) {
            $url = str_replace('//oss.', 'https://image.', $url);
        }

        return $url;
    }
}